import json
import traceback

import jsonpath

from commons.logger_util import logs, error_log


def assert_result(yq_result, sj_result, result_code):
    try:
        logs("预期结果：%s" % yq_result)
        logs("实际结果：%s" % json.loads(json.dumps(sj_result).replace(r"\\", "\\")))
        all_flag = 0
        for yq in yq_result:
            for key, value in yq.items():
                # 相等断言
                if key == "equals":
                    flag = equals_assert(value, sj_result, result_code)
                    all_flag = all_flag + flag
                # 包含断言
                elif key == "contains":
                    flag = contains_assert(value, sj_result)
                    all_flag = all_flag + flag
                # 大于断言
                elif key == "greater_than_assert":
                    flag = greater_than_assert(value, sj_result)
                    all_flag = all_flag + flag
                # 小于断言
                elif key == "less_than_assert":
                    flag = less_than_assert(value, sj_result)
                    all_flag = all_flag + flag
                else:
                    error_log("框架暂时不支持这种断言方式")
        assert all_flag == 0
        logs("接口断言成功")
        logs("接口测试成功")
        logs("--------接口测试结束--------\n")
    except Exception as e:
        logs("接口测试失败")
        logs("--------接口测试结束--------\n")
        error_log("断言assert_result失败：%s" % str(traceback.format_exc()))


# 相等断言
def equals_assert(value, sj_result, result_code):
    flag = 0
    for assert_key, assert_value in value.items():
        if assert_key == "status_code":
            if assert_value != result_code:
                flag = flag + 1
                logs("断言失败: 返回的状态码不等于%s,接口请求异常" % assert_value)
            else:
                logs("断言成功: 状态码" + assert_key + "等于" + str(assert_value))
        else:
            sj_value = jsonpath.jsonpath(sj_result, '$..%s' % assert_key)[0]
            # print(lists)
            if sj_value:
                if assert_value != sj_value:
                    flag = flag + 1
                    logs("断言失败: " + assert_key + "不等于" + str(assert_value))
                else:
                    logs("断言成功: " + assert_key + "等于" + str(assert_value))
        return flag


# 包含断言
def contains_assert(value, sj_result):
    flag = 0
    if str(value) not in str(sj_result):
        flag = flag + 1
        logs("断言失败:返回的结果中不包含：" + value)
    return flag


# 大于断言
def greater_than_assert(self, value, sj_result):
    flag = 0
    (assert_key, assert_value), = value.items()
    sj_value = (jsonpath.jsonpath(sj_result, '$..%s' % assert_key))[0]
    if assert_value >= sj_value:
        flag = flag + 1
        logs("大于断言失败")
    return flag


# 小于断言
def less_than_assert(self, value, sj_result):
    flag = 0
    (assert_key, assert_value), = value.items()
    sj_value = (jsonpath.jsonpath(sj_result, '$..%s' % assert_key))[0]
    if assert_value <= sj_value:
        flag = flag + 1
        logs("小于断言失败")
    return flag
